<?php

	/**
	 * Workspace@ Engine application comment!
	 * 
	 * LICENSE
	 * This application is licensed under New BSD license.
	 * Please read complete LICENSE.txt inside of root folder for more details.
	 * 
	 * We wish you good building :) 
	 * 
	 * @category   Application
	 * @package    Bootstrap
	 * @author     Nevio Vesic <nevio@workspaceat.com>
	 * @copyright  2008-2009 Workspace@ group in association with Design strategist
	 */

	class Engine_Plugins_Page extends Engine_Application_Abstract
	{
		public static $fuck = null;
		
		public static $lochost = null;
		
		const PAGE_EXTENSION   = ".phtml";
		
		protected $db          = null;
		
		const GROUPS_STANDALONE  = "standalone";
		
		const GROUPS_SUBMAIN     = "subgroups";
		
		/**
		 * Counter for building directories
		 * Don't fuk with it :D
		 */
		protected $counter = null;
		
		protected static $modificationType = null;
		
		function __construct()
		{
			if ( self::$lochost)
			{
				self::$lochost = null;
			}
			
			if ( self::$data['instance'] == "backend" )
			{
				self::$lochost = self::$system -> enviroment -> url . "backend/";
			}
			
			$this->db = $this->databaseInstance();
			
		}
		
		public function getPageBefore( )
		{
			if (! self::$fuck )
			{
				Zend_Registry::set("Latest_Page", false );
				self::$fuck = "ZZzzzZZzzzZ";
			}
			
			if ( @Zend_Registry::get("Latest_Page" ) )
			{
				return Zend_Registry::get("Latest_Page" );
			}
			
			return false;
		}
		
		public function setPageBefore( $href )
		{
			Zend_Registry::set("Latest_Page", false );
		}
		
		public function link( $loc )
		{
			if ( $loc )
			{
				return self::$lochost . $loc;
			}
			else{
				return self::$lochost;
			}
		}
		
		/**
		 * Backend url.
		 *
		 * @return Domain[Full]
		 */
		public function backendUrl()
		{
			return self::$system -> enviroment -> url . self::$system -> enviroment -> access -> element;
		}
		
		public function frontendUrl()
		{
			return self::$system -> enviroment -> url;
		}
		
		/**
		 * Check out if requested page already exists in database
		 * @return bool[true|false]
		 */
		public function isRegistred( $pagename )
		{
			
			$r = explode("/", $pagename );
			
			if(! $r[1] )
			{
				$page = $pagename;	
			}
			elseif ( $r[1] !== false )
			{
				$c = count($r);
				
				foreach ( $r as $items )
				{
					if ( $items !== "" )
					{
						$bb[] = $items;
					}
				}
				
				$page = $bb[$c-1];
				
				$groups = null;
				
				for( $i=0; $i<=$c; $i++)
				{
					if ( $i !== $c-1 && $r[$i] )
					{
						$groups .= $r[$i] . "/";
					}
				}
					
			}

			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			if (! $groups )
			{
				$sql_group = "0";
			}
			else
			{
				$sql_group = $groups;
			}
			
			$uname = strtolower($page);
			
			$result = $this->db->fetchRow("SELECT id FROM pages WHERE groups='{$sql_group}' AND unixname='{$uname}'" );
			
			
			if (! $result->id )
			{
				return false;
			}
			else
			{
				return true;
			}	
		}
		
		/**
		 * Allocate groups and return as Zend_Db object
		 *
		 * @param  mixed[main|subgroups] $type
		 * @return unknown
		 */
		public function allocateGroups($type)
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$preresult = $this->db->fetchAll( "SELECT * FROM pages" );
			
			if( $type == self::GROUPS_STANDALONE )
			{
				$sql = "SELECT * FROM pages WHERE standalone='true'";
			}
			elseif ( $type == self::GROUPS_SUBMAIN )
			{
				
			}
			else {
				throw new Engine_Exception( "Current allocation type missmatched. Use 'standalone' or 'subgroups'" );
			}
			
			$result = $this->db->fetchAll( $sql );
			return $result;
		}
		
		
		public function deletePage(Zend_Config $data )
		{
			// block if current page is standalone
			if ( $data -> standalone == "true" )
			{
				
				$result = $this->db -> query ("DELETE FROM pages WHERE id='$data->id' AND unixname = '{$data->page}' LIMIT 1");
				
				$builder = self::$plugins -> builder -> deletePage( $data->standalone, $data -> page );
				
				if ( $builder["status"] == "true" )
				{
					if ( $result )
					{
						return array (
							"status" => "true",
							"message" => "Message has been successfuly deleted! Please wait..."
						);
					}
					else
					{
						return array (
							"status" => "false",
							"message" => "There was a error with sql syntax! Page can't be deleted!"
						);
					}
				}
				else{
					return $builder;
				}
			}
			elseif ( $data -> standalone == "false" )
			{

			}
			else
			{
				// return false array for json!
				return array (
					"status" => "false",
					"message" => "Please use real types... Don't try to hack!"
				);
			}
		}
		
		public function setPageModificationType( $type )
		{
			if ( self::$modificationType )
			{
				self::$modificationType = null;
			}
			
			self::$modificationType = $type;
		}
		
		/**
		 * Get current page by id
		 *
		 * @param  number  $id
		 * @return Object[Zend_Db]
		 */
		public function getPageById( $id )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$result = $this->db->fetchRow("SELECT * FROM pages WHERE id ='{$id}' " );
			
			if (! $result )
			{
				throw new Engine_Exception( "Current page can't be founded! Please use it properly! Hacking isn't good way to do something!" );
			}
			
			return $result;
		}
		
		public function addPage(Zend_Config $data)
		{
			if ( $data->groupname == "0")
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "You must choose group! Please do that!"
				);
				die();
			}
			elseif (! $data->pagename || strlen($data->pagename) < 2 )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Page name can't be blank or smaller than 2 characters!"
				);
				die();
			}
			
			if (! $data->groupname == "standalone" )
			{
				$grouptype = "true";
				$groupid   = "0";
			}
			else{
				$grouptype = "false";
				$groupid   = $data->groupid;
			}
			
			# now lets go do the rest..
			$unixname = strtolower( $this->replaceChars( $data->pagename ) );
			
			# lets check if current page already exists in database
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			
			$sameresult = $this->db->fetchRow("SELECT id FROM pages WHERE garbaged='false'
			AND unixname='{$data->pagename}' AND groups='{$data->groupid}'");
			
			if ( $sameresult->id )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Current page exists in system. Please use dirrenent name."
				);
				die();
			}
			
			# ok current page doesn't exists so we go do something else
			# for now lets go and find out exact location of current group.
			# than we go and add page to that group
			# after that we go and do language file for that page.
			# if all success than we go and do simple query insertation for pages
			# if all pass well, we return true. Otherwize we return false and 
			# give response message to user so that he know what to do.
			# K? let's go do it :D
			
			if (! $data->groupid == "0" )
			{
				# let's trick counter :D
				if ( $this->counter )
				{
					$this->counter = null;
				}
				$this->counter = $data->parents;
				
				$fukit = null;
				
				while($this->counter !== 0 ){
					
					# do some nasty hack for while loop... I hate infinte loops 
					if (! $fukit )
					{
						$resultdir = $this->db->fetchRow ( "SELECT id, unixname, parentof 
						FROM page_groups WHERE id='{$data->groupid}' AND status='true'" );
						
						if ( $fukit )
						{
							$fukit = null;
						}
						$fukit = $resultdir->parentof;
					}
					else{
						$resultdir = $this->db->fetchRow ( "SELECT id, unixname, parentof 
						FROM page_groups WHERE id='{$fukit}' AND status='true'" );
						if ( $fukit )
						{
							$fukit = null;
						}
						$fukit = $resultdir->parentof;
					}
					
					$this->arrdata[] = strtolower( $resultdir->unixname );
					
					if ( $this->counter )
					{
						$this->counter = null;
					}
					$this->counter = $resultdir->parentof;
					
				}
				
				# used for adding paths so that we know last position
				$rpath = null;
				
				# lets reverse array for now
				$reversed = array_reverse( $this->arrdata );
				
				# ok lets now check if directories of array exists, if not create one.
				foreach ( $reversed as $path )
				{
					$rpath .= $path . DIRECTORY_SEPARATOR;
				}
				
				$path = $rpath;
				
			}else if ( $data->groupid == "0" )
			{
				# lets setup path :: standalone always none! THAT U DON't FORGET
				$path = "";	
			}
			
			# ok lets go built page for this group
			
			if ( self::$plugins->builder->createFrontendDir($path) )
			{
				# ok lets go now add current page
				if ( self::$plugins->builder->createPage($path, $unixname) )
				{
					
					# ok we have it lets go now to create language file
					if ( self::$plugins->builder->createLanguageFile($path, $unixname) )
					{
						
						if ( $data->groupname == "standalone" )
						{
							$grouptype = "true";
							$groupid   = "0";
						}
						else{
							$grouptype = "false";
							$groupid   = $data->groupid;
						}
						
						# ok lets go now to add new page into database
						$sqlhandler = $this->db->query ( "INSERT INTO pages ( garbaged, name, unixname, title, description, standalone,
						groups, status) VALUES ( 'false', '{$data->pagename}', '{$unixname}', 'Built page name title', 'This page doesn\'t got any description yet...', '{$grouptype}',
						'{$groupid}', 'false')" );
						
						if (! $sqlhandler )
						{
							return array (
								"status" => "false",
								"input"  => "",
								"message" => "There was some problem with sql insertation!"
							);
							die();	
						}
						
							return array (
								"status" => "true",
								"input"  => "",
								"message" => "Page has been successfully created! Please wait..."
							);
							die();	
					}
					else 
					{
						return array (
							"status" => "false",
							"input"  => "",
							"message" => "There was some problem with creating laguage file!"
						);
						die();	
					}
					
				}else
				{
					return array (
						"status" => "false",
						"input"  => "",
						"message" => "There was some problem with creating page file!"
					);
					die();	
				}
				
			}else{
				return array (
					"status" => "false",
					"input"  => "",
					"message" => "There was some problem with creating folder!"
				);
				die();
			}
		}
		
		/**
		 * Stupid function for replacing illegal characters with "" and white spaces with -
		 *
		 * @param  string $str
		 * @return string
		 */
		private function replaceChars($str)
		{
			$a = str_replace("`", "", $str );
			$b = str_replace("~", "", $a   );
			$c = str_replace("`", "", $b   );
			$d = str_replace("!", "", $c   );
			$e = str_replace("@", "", $d   );
			$f = str_replace("#", "", $e   );
			$g = str_replace("$", "", $f   );
			$h = str_replace("%", "", $g   );
			$i = str_replace("^", "", $h   );
			$j = str_replace("&", "", $i   );
			$k = str_replace("*", "", $j   );
			$l = str_replace("(", "", $k   );
			$m = str_replace(")", "", $l   );
			$n = str_replace("}", "", $m   );
			$o = str_replace("{", "", $n   );
			$p = str_replace("[", "", $o   );
			$r = str_replace("]", "", $p   );
			$s = str_replace(":", "", $r   );
			$t = str_replace("\\", "", $s   );
			$u = str_replace("/", "", $t   );
			$v = str_replace("'", "", $u   );
			$x = str_replace("\"", "", $v   );
			$y = str_replace("|", "", $x   );
			$z = str_replace("<", "", $y   );
			$a1 = str_replace(">", "", $z   );
			$a2 = str_replace(";", "", $a1   );
			$a3 = str_replace(" ", "-", $a2   );
			$a4 = str_replace("=", "", $a3   );
			$a5 = str_replace(",", "", $a4   );
			$a6 = str_replace(".", "_", $a5   );
			$a7 = str_replace(" ", "-", $a6   );
			return $a7;
		}
		
	}

